package org.pictual.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;
import org.pictual.controller.WikiDescargaOGG;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class GetAudio{

	private String pathogg;
	private String pathmp3;
	
	protected static Logger log= Logger.getLogger(GetAudio.class);

	
	public GetAudio(String word, String language){
		try {
			String audio="http://apifree.forvo.com/action/word-pronunciations/format/xml/word/"+word+"/language/"+language+"/limit/1/key/ac7a1150dd0819a3ee77865934f97eca/";
			URL url= new URL(audio);
			WikiDescargaOGG.uploadImageByFTP(audio);
			BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
			String entrada;
			String cadena="";

			while ((entrada = br.readLine()) != null){
				cadena = cadena + entrada;
			}

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();

			InputSource archivo = new InputSource();
			archivo.setCharacterStream(new StringReader(cadena)); 

			Document documento = db.parse(archivo);
			documento.getDocumentElement().normalize();

			NodeList items = documento.getElementsByTagName("item");

			for (int s = 0; s < items.getLength(); s++) {

				Node item = items.item(s);

				if (item.getNodeType() == Node.ELEMENT_NODE) {

					Element elementoOGG = (Element) item;

					NodeList nodeOGG = elementoOGG.getElementsByTagName("pathogg");
					Element primerNombreElementoOGG = (Element) nodeOGG.item(0);
					NodeList primerNombreOGG = primerNombreElementoOGG.getChildNodes();
					pathogg = ((Node) primerNombreOGG.item(0)).getNodeValue().toString();
					log.info("pathogg : "  + pathogg);
					
					Element elementoMP3 = (Element) item;

					NodeList nodeMP3 = elementoMP3.getElementsByTagName("pathmp3");
					Element primerNombreElementoMP3 = (Element) nodeMP3.item(0);
					NodeList primerNombreMP3 = primerNombreElementoMP3.getChildNodes();
					pathmp3 = ((Node) primerNombreMP3.item(0)).getNodeValue().toString();
					log.info("pathmp3 : "  + pathmp3);



				}
			}
		}
		catch (Exception e) {
			log.error("Error al obtener el audio");
		}
		
		
	}
	
	public String getPathmp3() {
		return pathmp3;
	}
	
	public String getPathogg() {
		return pathogg;
	}
	
	public void setPathmp3(String pathmp3) {
		this.pathmp3 = pathmp3;
	}
	
	public void setPathogg(String pathogg) {
		this.pathogg = pathogg;
	}
	
	public static void main(String[] args) {
		log.info(new GetAudio("casa", "es").getPathogg());
	}
}
